package com.atguigu.controller.front;

import com.atguigu.client.OrdersClient;
import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.commonutils.ordervo.CourseWebOrder;
import com.atguigu.entity.EduCourse;
import com.atguigu.entity.chapter.ChapterVo;
import com.atguigu.entity.frontvo.CourseFrontVo;
import com.atguigu.entity.frontvo.CourseWebVo;
import com.atguigu.service.EduChapterService;
import com.atguigu.service.EduCourseService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.jsonwebtoken.Jwt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/eduservice/coursefront")
public class CourseFrontController {

    @Autowired
    private EduCourseService courseService;

    @Autowired
    private EduChapterService chapterService;

    @Autowired
    private OrdersClient ordersClient;

    //1、条件查询带分页查询课程
    @PostMapping("/getFrontCourseList/{page}/{limit}")
    public R getFrontCourseList(@PathVariable Long page,
                                @PathVariable Long limit,
                                @RequestBody(required = false) CourseFrontVo courseFrontVo) {
        Page<EduCourse> pageCourse = new Page<>(page, limit);

        Map<String, Object> map =  courseService.getCourseFrontList(pageCourse, courseFrontVo);

        return R.ok().data(map);
    }

    //2、课程详情的方法
    @GetMapping("/getFrontCourseInfo/{courseId}")
    public R getFrontCourseInfo(@PathVariable String courseId, HttpServletRequest request){
        //根据课程id，编写sql语句查询课程信息
        CourseWebVo courseWebVo = courseService.getBaseCpirseInfo(courseId);

        //根据课程id查询章节和小节
        List<ChapterVo> list = chapterService.getChapterVideoByCourseId(courseId);

        //根据课程id和用户id查询当前课程是否已经支付
        boolean buyCourse = false;

        String jwtToken = request.getHeader("token");
        if(jwtToken != null){
            System.out.println("已登录");
            String memberId = JwtUtils.getMemberIdByJwtToken(request);

            buyCourse = ordersClient.isBuyCourse(courseId, memberId);
        }

        return R.ok().data("courseWebVo", courseWebVo).data("list", list).data("isBuy", buyCourse);
    }

    //3、根据课程id查询课程信息
    @PostMapping("/getCourseInfoOrder/{id}")
    public CourseWebOrder getCourseInfoOrder(@PathVariable String id){
        CourseWebVo courseWebVo = courseService.getBaseCpirseInfo(id);
        CourseWebOrder orderWebOrder = new CourseWebOrder();
        BeanUtils.copyProperties(courseWebVo, orderWebOrder);
        return orderWebOrder;
    }
}
